﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using SCSEngine.Services;
using Microsoft.Xna.Framework.Input.Touch;
using SCSEngine.ResourceManagement;
using TriUan.TriUanGame.GameScreen;
using SCSEngine.Sprite;
using SVLvsXNA.Facebook;
using TriUan;
using TextEffect;
using TriUan.SCSEngine.Utils;
namespace SVLvsXNA
{
    public partial class GamePage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;

        SCSServices scsServices; 
        TriUanScreenManager screenManager;

        public GameServiceContainer Services { get; private set; }
        public ContentManager Content { get; private set; }

        public bool IsBackKeyPress = false;

        public GamePage()
        {
            InitializeComponent();

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;
            Content = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;
            GameInformation.Init(new CTextEffect().LoadTextFromFile("Content/GameInformation.triuan"));
            this.Services = new GameServiceContainer();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            scsServices = new SCSServices(this, spriteBatch);
            Services.AddService(typeof(SCSServices), scsServices);

            // TODO: use this.content to load your game content here

            TouchPanel.EnabledGestures = GestureType.Tap | GestureType.FreeDrag | GestureType.Hold | GestureType.HorizontalDrag | GestureType.VerticalDrag | GestureType.Flick;
            IResourceManager resourceManager = new SCSResourceManager(this.contentManager);
            this.Services.AddService(typeof(IResourceManager), resourceManager);

            LoadSpriteData();

            screenManager = new TriUanScreenManager(this);

            // Current Menu
            screenManager.AddExclusive(screenManager.Bank.GetNewScreen("Menu"));

            // Start the timer
            timer.Start();

            //var par = new Dictionary<string, object>();

            //FacebookServices.GetInstanse().GetAsync("/me", (o, ex) =>
            //    {
            //        if (ex.Error != null)
            //        {
            //            Dispatcher.BeginInvoke(() => MessageBox.Show(ex.Error.Message));
            //            return;
            //        }
            //        var result = (IDictionary<string, object>)ex.GetResultData();
            //        int a;
            //        a = 1;
            //    });
            Camera2D.Pos = Vector2.Zero;
            Camera2D.Zoom = 1f;

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            scsServices.InputHandle.Update(); 
            screenManager.Update(new GameTime(e.TotalTime, e.ElapsedTime));
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (!(screenManager.Current is MenuScreen))
            {
                IsBackKeyPress = true;
                e.Cancel = true;
            }
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            screenManager.Draw(new GameTime(e.TotalTime, e.ElapsedTime));

            spriteBatch.End();
        }

        protected void LoadSpriteData()
        {
            SpriteFramesBank.Instance.Add("play", FramesGenerator.Generate(49, 49, 49, 1));
            SpriteFramesBank.Instance.Add("ScareCrow_Classic", FramesGenerator.Generate(232, 224, 928, 4));
            SpriteFramesBank.Instance.Add("ScareCrow_Creative", FramesGenerator.Generate(187, 177, 748, 4));
            SpriteFramesBank.Instance.Add("ScareCrow_FreeStyle", FramesGenerator.Generate(249, 238, 996, 4));

            SpriteFramesBank.Instance.Add("Item", FramesGenerator.Generate(122, 164, 978, 8));
        }
    }
}